package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.CategoryService;
import com.itheima.bean.Category;
import com.itheima.bean.Params;

import com.itheima.bean.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/category")
@RestController
public class CategoryController {

    @Autowired
    private CategoryService cs;

    @GetMapping("/list")
    public R findUserPage(){
//     List<DishDto> list = cs.findfindUserPage();
     List<Category> list = cs.findfindUserPage();


     return R.success(list);
    }

    @GetMapping("/type/{type}")
    public R findByType(@PathVariable int type){

        try {
            List<Category> list= cs.findByType(type);
            return R.success(list);
        } catch (Exception e) {
            e.printStackTrace();
           return R.error("查询分页数据失败！");
        }
    }

    @PutMapping
    public R update(@RequestBody Category category){
        int row = cs.update(category);
        if (row>0){
            return R.success("修改成功！");
        }else {
            return R.error("修改失败！");
        }
    }



    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id){
        int row = cs.delete(id);
       /* if (row==1){
            return R.success("删除成功！");
        }else if (row==-1){
            return R.error("此数据关联其他表格，无法删除！");
        }else {

            return R.error("删除失败！");
        }*/
        if (row>0){
            return R.success("删除成功！");
        }else {

            return R.error("删除失败！");
        }
    }

    @PostMapping
    public R<String> add(@RequestBody Category category){

        int row = cs.add(category);
        if (row>0){
            return R.success("分类新增成功！");
        }else {
            return R.error("分类新增失败");
        }
    }

    @GetMapping("/{param}")
    public R findPage(@PathVariable String param){
        Params params =JSON.parseObject(param,Params.class);
        IPage<Category> page = cs.findPage(params);

        return R.success(page);
    }

}
